_Pragma("once");

#include <vector>
#include <cstddef>
#include "ExtendDeviceType.h"

#include "MachineDependents.h"

template <class DEVICE_CONTROLLER>
class MultiPortDeviceManager {
public:

    virtual ~MultiPortDeviceManager() {
    }

    void initialize(const ExtendDeviceType& extendDeviceType) {
        mpControllers = &ExtendDeviceManagerSingleton::instance().getExtendDevices(extendDeviceType);

        mportCount = 0;
    }

    size_t updatePortCount();

    std::shared_ptr<DEVICE_CONTROLLER> locateController(size_t& portNo) {
        size_t indexCount = 0;
        std::shared_ptr<DEVICE_CONTROLLER> extendDevicePtr;
        for (ExtendDeviceWeakPtr& loopDeviceWeakPtr : *mpControllers) {
            extendDevicePtr = std::static_pointer_cast<DEVICE_CONTROLLER>(loopDeviceWeakPtr.lock());
            if (!extendDevicePtr) {
                continue;
            }

            if (indexCount + extendDevicePtr->mportCount > portNo) {
                portNo -= indexCount;
                return extendDevicePtr;
            }
            indexCount += extendDevicePtr->mportCount;
        }

        extendDevicePtr.reset();
        return extendDevicePtr;
    }


public:
    /**
     * 控制外设的集合
     */
    std::vector<ExtendDeviceWeakPtr>* mpControllers;
    /*
     * 设备通道数
     */
    size_t mportCount = 0;
};


template <class DEVICE_CONTROLLER>
size_t MultiPortDeviceManager<DEVICE_CONTROLLER>::updatePortCount() {
    size_t portCount = 0;
    ExtendDevicePtr extendDevicePtr;
    DEVICE_CONTROLLER* pController;
    for (ExtendDeviceWeakPtr& loopDeviceWeakPtr : *mpControllers) {
        extendDevicePtr = loopDeviceWeakPtr.lock();
        if (!extendDevicePtr) {
            continue;
        }
        pController = static_cast<DEVICE_CONTROLLER*> (&*extendDevicePtr);
        portCount += pController->mportCount;
    }
    mportCount = portCount;

    return mportCount;
}
